<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue'
import { getAll, addApi, queryByIdApi, updateApi, deleteApi, getCityList } from '@/api/supplier'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = ref({
  supplierName: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据列表
const projectList = ref([])
const citylist = ref([])
const loading = ref(false)

// 对话框相关
const open = ref(false)
const title = ref('')
const projectRef = ref(null)

// 树形结构配置（适配pcd表结构）
const treeProps = ref({
  children: 'children',
  label: 'name',
  value: 'id'
})

// 表单数据（与数据库字段对应）
const form = reactive({
  id: null,
  supplierName: '', // 对应supplier_name
  linkName: '',     // 对应link_name
  linkPhone: '',    // 新增：联系人手机号
  cityCode: null,   // 对应city_code
  provinceId: null, // 新增：省份ID
  address: ''       // 对应address
})

// 表单验证规则


// 获取城市列表（树形结构）
const getCityData = async () => {
  try {
    const res = await getCityList()
    const rawData = res.data || res
    
    // 构建省市区树形结构（适配pcd表）
    if (Array.isArray(rawData)) {
      citylist.value = buildCityTree(rawData)
    } else {
      citylist.value = rawData
    }
  } catch (error) {
    ElMessage.error('获取城市列表失败: ' + error.message)
    console.error(error)
  }
}

// 构建城市树形结构（处理pcd表数据）
const buildCityTree = (data) => {
  const map = {}
  const roots = []

  // 初始化所有节点
  data.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  // 构建树形结构（parent_id=0为根节点即省份）
  data.forEach(item => {
    const node = map[item.id]
    if (item.parent_id === 0 || item.parent_id === '0' || !item.parent_id) {
      roots.push(node)
    } else {
      const parent = map[item.parent_id]
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  // 按sort字段排序
  const sortNodes = (nodes) => {
    return nodes.sort((a, b) => (a.sort || 0) - (b.sort || 0)).map(node => {
      if (node.children && node.children.length) {
        node.children = sortNodes(node.children)
      }
      return node
    })
  }

  return sortNodes(roots)
}

// 选择城市时自动获取省份ID
const handleCityChange = (value) => {
  if (!value) {
    form.provinceId = null
    return
  }
  
  // 从树形数据中查找选中节点的省份ID
  const findProvince = (nodes, targetId) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        // 如果是省份(level=1)，自身即为省份ID
        if (node.level === 1) return node.id
        // 如果是市或区，递归查找父节点
        return findProvince(citylist.value, node.parent_id)
      }
      if (node.children && node.children.length) {
        const result = findProvince(node.children, targetId)
        if (result) return result
      }
    }
    return null
  }
  
  form.provinceId = findProvince(citylist.value, value)
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  try {
    const res = await getAll(
      queryParams.value.supplierName, 
      currentPage.value, 
      pageSize.value
    )
    projectList.value = res.data?.rows || res.data || []
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('查询失败: ' + error.message)
    console.error(error)
    projectList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.value.supplierName = ''
  currentPage.value = 1
  handleQuery()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  handleQuery()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleQuery()
}

// 新增
const handleAdd = () => {
  resetForm()
  title.value = '新增供应商'
  open.value = true
}

// 修改
const handleUpdate = async (row) => {
  title.value = '修改供应商'
  
  try {
    // 获取详情
    const res = await queryByIdApi(row.id)
    const data = res.data || res
    // 填充表单（注意字段映射）
    form.id = data.id
    form.supplierName = data.supplierName
    form.linkName = data.linkName
    form.linkPhone = data.linkPhone
    form.cityCode = data.cityCode
    form.provinceId = data.provinceId
    form.address = data.address
    open.value = true
  } catch (error) {
    ElMessage.error('获取详情失败: ' + error.message)
    console.error(error)
  }
}

// 删除
const handleDelete = async (row) => {
 
    const res = await deleteApi(row.id)
    if (res.code) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  
}

// 提交表单
const submitForm = async () => {
  if (!projectRef.value) return
  
  try {
    // 表单验证
    await projectRef.value.validate()
    
    // 构造提交数据（字段映射）
    const submitData = {
      id: form.id,
      supplier_name: form.supplierName,
      link_name: form.linkName,
      link_phone: form.linkPhone,
      city_code: form.cityCode,
      province_id: form.provinceId,
      address: form.address
    }
    
    let res
    if (form.id) {
      // 修改操作
      res = await updateApi(submitData)
    } else {
      // 新增操作
      res = await addApi(submitData)
    }
    
    if (res.code) {
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      open.value = false
      handleQuery()
    } else {
      ElMessage.error(res.msg || (form.id ? '修改失败' : '新增失败'))
      open.value = false
      handleQuery()
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.supplierName = ''
  form.linkName = ''
  form.linkPhone = ''
  form.cityCode = null
  form.provinceId = null
  form.address = ''
  
  

}

// 取消
const cancel = () => {
  open.value = false

}

// 页面加载时初始化
onMounted(() => {
  handleQuery()
  getCityData()
})
</script>

<template>
  <div class="supplier-management">
    <!-- 查询表单 -->
    <el-form :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input 
          v-model="queryParams.supplierName" 
          placeholder="请输入名称" 
          clearable 
          @keyup.enter="handleQuery" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operate-btn" style="margin: 10px 0;">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="projectList" 
      border 
      style="width: 100%;"
    >
      <el-table-column label="编号" align="center" type="index" width="120px" />
      <el-table-column label="供应商" align="center" prop="supplierName" width="150px" />
      <el-table-column label="联系人" align="center" prop="linkName" width="150px" />
      <el-table-column label="联系电话" align="center" prop="linkPhone" width="150px" />
      <el-table-column label="省份" align="center" prop="provinceId" width="120px" />
      <el-table-column label="城市" align="center" prop="cityCode" width="120px" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column 
        label="操作" 
        align="center" 
        width="200px" 
        fixed="right" 
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block" style="margin-top: 10px; text-align: right;">
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize" 
        :page-sizes="[5, 10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper" 
        :total="total" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
      />
    </div>

    <!-- 新增/修改对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="500px" 
      append-to-body
    >
      <el-form 
        ref="projectRef" 
        :model="form" 
       
        label-width="80px"
      >
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="linkName">
          <el-input v-model="form.linkName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="linkPhone">
          <el-input v-model="form.linkPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="城市" prop="cityCode">
          <el-tree-select
            v-model="form.cityCode"
            :data="citylist"
            :props="treeProps"
            placeholder="请选择省/市/区"
            clearable
            check-strictly
            style="width: 100%"
            @change="handleCityChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.supplier-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.operate-btn {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}
</style>